import router, { asyncRoutes, companyRoutes, constantRoutes } from '@/router'

/* eslint-disable */

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route)
{
  if (route.meta && route.meta.roles)
  {
    return roles.some(role => route.meta.roles.includes(role))
    // return route.meta.roles.some(role => route.meta.roles.includes(role))
  } else
  {
    return true
  }
}

function getPath(route)
{
  import('@/views/' + (route))
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
/* export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.component === 'Layout') { // Layout组件特殊处理
        tmp.component = Layout
      } else {
        // tmp.component = getPath(tmp.component)
        tmp.component = () => import('@/' + (tmp.component))
        // tmp.component = () => import('@/views/user/admin')
        // console.log(tmp.component)
      }
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
} */

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) =>
  {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles)
  {
    // 正式为，解开注释，删掉下面的
    /* return new Promise(resolve => getRoutes().then(res => {
      var route = ''
      route = filterAsyncRoutes(res.data, roles)
      commit('SET_ROUTES', route)
      resolve(route)
    })
    ) */
    return new Promise(resolve =>
    {
      const accessedRoutes = asyncRoutes || []
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  generateCompanyRoutes({ commit }, roles)
  {
    return new Promise(resolve =>
    {
      commit('SET_ROUTES', companyRoutes)

      resolve(companyRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
